package com.haipumi.servlets.backadmin;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.haipumi.beans.DataGrid;
import com.haipumi.beans.JsonModel;
import com.haipumi.beans.haipumi_admins;
import com.haipumi.beans.haipumi_user;
import com.haipumi.biz.IBackAdminBiz;
import com.haipumi.biz.impl.BackAdminBizImpl;
import com.haipumi.dao.IBackAdminDao;
import com.haipumi.servlets.CommonServlet;
import com.haipumi.utils.CommonData;
import com.haipumi.utils.RequestUtil;

public class BackAdminServlet extends CommonServlet {

	
	IBackAdminBiz ibab=new BackAdminBizImpl();
	JsonModel jm=new JsonModel();
	DataGrid dg=new DataGrid();
	/**
	 * 
	 */
	private static final long serialVersionUID = -7391120529329892382L;

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//先从request里获取op选项为多少
		String op=request.getParameter("op");
		
		if("backlogout".equals(op)){
			backlogout(request,response);
		}else if("findAllAdmins".equals(op)){
			findAllAdmins(request,response);
		}else if("saveAdmin".equals(op)){
			saveAdmin(request,response);
		}else if("editAdmin".equals(op)){
			editAdmin(request,response);
		}
				
	}

	private void editAdmin(HttpServletRequest request,
			HttpServletResponse response) {
		haipumi_admins admin=null;
		haipumi_admins backadmin=null;
		admin=RequestUtil.parseRequest(request, haipumi_admins.class);
		backadmin=ibab.editAdmin(admin);
		if(backadmin==null){
			//修改失败了,恢复原来的表格
			backadmin=ibab.findAdmin(admin.getAid());
		}
		super.outData(response, backadmin);
	}

	private void saveAdmin(HttpServletRequest request,
			HttpServletResponse response) {
		Boolean isNewRecord=Boolean.parseBoolean(request.getParameter("isNewRecord"));
		haipumi_admins admin=null;
		haipumi_admins backadmin=null;
		try {
			admin = RequestUtil.parseRequest(request, haipumi_admins.class);
			if(isNewRecord){
				//新增的
				backadmin=ibab.insertAdmin(admin);
			}else{
				//编辑的 
			}
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		super.outData(response, backadmin);
		
	}

	private void findAllAdmins(HttpServletRequest request,
			HttpServletResponse response) {
		List<haipumi_admins>admins=ibab.findAllAdmins();
		int r=ibab.countAllAdmins();
		dg.setTotal(r);
		dg.setRows(admins);
		super.outData(response, dg);
		
	}

	private void backlogout(HttpServletRequest request,
			HttpServletResponse response) {
		HttpSession session=request.getSession();
		session.removeAttribute(CommonData.ADMINSESSION);
		
		jm.setCode(1);
		super.outData(response, jm);
	}

	

}
